package mypack.srverlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private final String PATH="D:/upload"; 
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	     doPost(request, response);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
       response.setContentType("text/plain");
       PrintWriter pw = response.getWriter();
       try{
    	   DiskFileItemFactory factory = new DiskFileItemFactory();
    	   factory.setRepository(new File(PATH));
    	   factory.setSizeThreshold(4*1024);
    	   ServletFileUpload upload = new ServletFileUpload(factory);
    	   upload.setSizeMax(4*1024*1024);
    	   List<FileItem> list = upload.parseRequest(request);
    	   Map<String,Object> map = new HashMap<String, Object>();
    	   for(FileItem item : list){
			   if(item.isFormField()){
				   processFormField(item,pw,map); 
			   } else {
				   processUploadFile(item,pw,map); 
			   }
    	   }
       }catch(Exception e){
    	   e.printStackTrace();
       }
       
	}
	
	  private void processFormField(FileItem item,PrintWriter pw,Map<String,Object> map){
   	     String name = item.getFieldName();
   	     String value = item.getString();
   	     map.put(name, value);
   	     pw.write(name+"----------------------->"+value+"\r\n");
      }
	
      private void processUploadFile(FileItem item,PrintWriter pw,Map<String,Object> map) throws Exception{
    	 String filename = item.getName();
    	 long filesize = item.getSize();
    	 if("".equals(filename)||filesize==0){
    		 return;
    	 }
    	 filename = filename.substring(filename.lastIndexOf("\\")+1);
    	 File file = new File(PATH+"/"+filename);
    	 item.write(file);
    	 pw.write(filename+" has saved,the size of size is "+filesize);
      }
	
	
	
	
	
}
